<template>
  <div class="prompt-edit-container">
    <!-- 主要内容区域 -->
    <div class="edit-content">
      <!-- 左侧表单区域 -->
      <div class="form-section">
        <div class="form-content">
          <n-form
            ref="formRef"
            :model="formData"
            :rules="rules"
            label-placement="top"
            class="template-form"
          >
            <div class="row-flex">
              <n-form-item label="模板名称" path="name" class="flex-item">
                <n-input 
                  v-model:value="formData.name" 
                  placeholder="输入模板名称"
                  size="large"
                />
              </n-form-item>
              <n-form-item label="分类" path="category" class="flex-item">
                <n-select
                  v-model:value="formData.category"
                  :options="categoryOptions"
                  placeholder="选择分类"
                  size="large"
                  filterable
                  allow-create
                />
              </n-form-item>
            </div>
            <n-form-item label="描述" path="description">
              <n-input
                v-model:value="formData.description"
                placeholder="输入模板描述"
                size="large"
              />
            </n-form-item>
          </n-form>
          <div class="prompt-area">
            <div class="prompt-label">系统提示词</div>
            <n-input
              v-model:value="formData.content"
              type="textarea"
              placeholder="输入系统提示词内容..."
              :autosize="{ minRows: 8, maxRows: 16 }"
              class="prompt-textarea system-prompt-textarea"
            />
            <div class="prompt-label">用户消息</div>
            <n-input
              v-model:value="formData.userMessage"
              type="textarea"
              placeholder="输入用户消息内容..."
              :autosize="{ minRows: 3, maxRows: 6 }"
              class="prompt-textarea user-message-textarea"
            />
          </div>
        </div>
        <!-- 底部按钮和模型选择器 -->
        <div class="form-actions-row">
          <div class="model-switch-btn">
            <ModelSelector :current-model="formData.model" @select-model="val => formData.model = val" />
          </div>
          <div class="form-actions">
            <n-button 
              type="primary" 
              @click="saveTemplate" 
              :loading="saving"
              size="large"
            >
              保存
            </n-button>
            <n-button 
              type="info" 
              @click="testTemplate" 
              :loading="testing"
              size="large"
            >
              测试
            </n-button>
          </div>
        </div>
      </div>

      <!-- 右侧预览区域 -->
      <div class="preview-section">
        <div class="preview-header">
          <h3>预览结果</h3>
          <div class="preview-actions">
            <n-button 
              quaternary 
              circle 
              size="small"
              @click="copyTestResult"
              :disabled="!testMessage.content && !testResult"
            >
              <template #icon>
                <n-icon><CopyOutline /></n-icon>
              </template>
            </n-button>
            <n-button 
              quaternary 
              circle 
              size="small"
              @click="clearTestResult"
              :disabled="!testMessage.content && !testResult"
            >
              <template #icon>
                <n-icon><TrashOutline /></n-icon>
              </template>
            </n-button>
          </div>
        </div>
        <div class="preview-content">
          <div v-if="!testMessage.content && !testResult" class="empty-preview">
            <n-empty description="请输入提示词内容并点击测试按钮">
              <template #icon>
                <n-icon size="60" color="#d9d9d9">
                  <DocumentTextOutline />
                </n-icon>
              </template>
            </n-empty>
          </div>
          
          <div v-else class="preview-text">
            <StreamMessage 
              :message="testMessage" 
              :safe-markdown-render="renderMarkdown"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { NForm, NFormItem, NInput, NSelect, NButton, NIcon, useMessage } from 'naive-ui'
import {
  DocumentTextOutline,
  CopyOutline,
  TrashOutline
} from '@vicons/ionicons5'
import { promptService } from '../services/prompt-service'
import ModelSelector from '../../chat/components/ModelSelector.vue'
import StreamMessage from '../../chat/components/StreamMessage.vue'
import { useModelStore } from '../../shared/stores/model'
import { useMarkdownRender } from '../../shared/composables/useMarkdownRender'

const route = useRoute()
const message = useMessage()
const modelStore = useModelStore()
const { renderMarkdown } = useMarkdownRender()

// 响应式数据
const saving = ref(false)
const testing = ref(false)
const testResult = ref('')
const formRef = ref()

// 模拟的 ChatMessage 对象，用于 StreamMessage 组件
const testMessage = ref({
  id: 'test-message',
  type: 'assistant' as const,
  content: '',
  status: 'thinking' as 'thinking' | 'streaming' | 'completed' | 'error',
  isStreaming: false,
  thinking: '',
  model: '',
  timestamp: Date.now()
})

// 表单数据
const formData = ref({
  id: null as number | null,
  name: '',
  content: '',
  category: '',
  description: '',
  userMessage: '',
  model: 0
})

// 判断是否为编辑模式
const isEdit = computed(() => {
  return route.params.id !== 'new'
})

// 分类选项
const categoryOptions = [
  { label: '通用', value: '通用' },
  { label: '灵感', value: '灵感' },
  { label: '大纲', value: '大纲' },
  { label: '章节规划', value: '章节规划' },
  { label: '支线', value: '支线' },
  { label: '细纲', value: '细纲' },
  { label: '人设', value: '人设' },
  { label: '正文', value: '正文' },
  { label: '封面', value: '封面' },
  { label: '审稿', value: '审稿' },
  { label: '改稿', value: '改稿' }
]

// 表单验证规则
const rules = {
  name: {
    required: true,
    message: '请输入模板名称',
    trigger: 'blur'
  },
  content: {
    required: true,
    message: '请输入提示词内容',
    trigger: 'blur'
  },
  category: {
    required: true,
    message: '请选择分类',
    trigger: 'change'
  }
}

const copyTestResult = async () => {
  const contentToCopy = testMessage.value.content || testResult.value
  if (!contentToCopy) return
  try {
    await navigator.clipboard.writeText(contentToCopy)
    message.success('复制成功')
  } catch (error) {
    message.error('复制失败，请手动复制')
  }
}

const clearTestResult = () => {
  testResult.value = ''
  testMessage.value.content = ''
  testMessage.value.status = 'thinking'
  testMessage.value.isStreaming = false
  testMessage.value.thinking = ''
}

const loadTemplate = async (id: string) => {
  try {
    const response = await promptService.getPromptTemplateById(parseInt(id))
    if (response.code === 0 && response.data) {
      const data = response.data
      formData.value = {
        id: data.id,
        name: data.name,
        content: data.content,
        category: data.category || '',
        description: data.description || '',
        userMessage: '',
        model: Number(data.model) || Number(modelStore.currentChatModel) || 0
      }
    } else {
      message.error('加载模板失败: ' + response.msg)
    }
  } catch (error: any) {
    message.error('加载模板失败: ' + error.message)
  }
}

const saveTemplate = async () => {
  try {
    await formRef.value?.validate()
    saving.value = true
    const submitData = {
      ...formData.value
    }
    if (isEdit.value && formData.value.id) {
      const response = await promptService.updatePromptTemplate(formData.value.id, submitData)
      if (response.code === 0) {
        message.success('模板更新成功')
      } else {
        message.error('更新失败: ' + response.msg)
      }
    } else {
      const { id, ...createData } = submitData
      const response = await promptService.createPromptTemplate(createData)
      if (response.code === 0) {
        message.success('模板创建成功')
      } else {
        message.error('创建失败: ' + response.msg)
      }
    }
  } catch (error: any) {
    if (error.message) {
      message.error('保存失败: ' + error.message)
    }
  } finally {
    saving.value = false
  }
}

const testTemplate = async () => {
  if (!formData.value.content) {
    message.warning('请先输入系统提示词内容')
    return
  }
  
  if (!formData.value.userMessage) {
    message.warning('请先输入用户消息内容')
    return
  }
  
  testing.value = true
  testResult.value = ''
  
  // 重置测试消息状态
  testMessage.value.content = ''
  testMessage.value.status = 'thinking'
  testMessage.value.isStreaming = false
  testMessage.value.thinking = ''
  testMessage.value.model = String(formData.value.model || Number(modelStore.currentChatModel))
  
  try {
    // 使用新的提示词模板测试流式接口，参考ai-service.ts的实现方式
    await promptService.testPromptTemplateStream(
      formData.value.userMessage,
      formData.value.content,
      formData.value.model || Number(modelStore.currentChatModel),
      {
        onMessage: (data) => {
          testMessage.value.status = 'streaming'
          testMessage.value.isStreaming = true
          testResult.value = data.data
          testMessage.value.content = data.data
        },
        onComplete: () => {
          testMessage.value.status = 'completed'
          testMessage.value.isStreaming = false
          testing.value = false
        },
        onError: (error) => {
          message.error('测试失败: ' + error.message)
          // 如果API调用失败，显示模拟结果
          const fallbackContent = `# 测试结果\n\n这是一个使用您的提示词模板生成的示例回复。\n\n## 功能特点\n\n- **智能分析**：基于您提供的系统提示词\n- **上下文理解**：能够理解复杂的指令\n- **格式规范**：支持Markdown格式输出\n\n## 使用建议\n\n1. 确保提示词描述清晰明确\n2. 包含具体的输出格式要求\n3. 指定期望的角色和行为\n\n> 提示：您可以根据实际需求调整提示词内容，以获得更好的效果。`
          
          testResult.value = fallbackContent
          testMessage.value.content = fallbackContent
          testMessage.value.status = 'completed'
          testMessage.value.isStreaming = false
          testing.value = false
        }
      }
    )
  } catch (error: any) {
    message.error('测试失败: ' + error.message)
    // 如果API调用失败，显示模拟结果
    const fallbackContent = `# 测试结果\n\n这是一个使用您的提示词模板生成的示例回复。\n\n## 功能特点\n\n- **智能分析**：基于您提供的系统提示词\n- **上下文理解**：能够理解复杂的指令\n- **格式规范**：支持Markdown格式输出\n\n## 使用建议\n\n1. 确保提示词描述清晰明确\n2. 包含具体的输出格式要求\n3. 指定期望的角色和行为\n\n> 提示：您可以根据实际需求调整提示词内容，以获得更好的效果。`
    
    testResult.value = fallbackContent
    testMessage.value.content = fallbackContent
    testMessage.value.status = 'completed'
    testMessage.value.isStreaming = false
  } finally {
    testing.value = false
  }
}

// 生命周期
onMounted(() => {
  const id = route.params.id as string
  // 获取默认模型（从store获取chat类型的默认模型）
  if (!isEdit.value) {
    formData.value.model = Number(modelStore.currentChatModel) || 0
  }
  if (id && id !== 'new') {
    loadTemplate(id)
  }
})
</script>

<style scoped>
.prompt-edit-container {
  height: calc(100vh - 90px);
  display: flex;
  flex-direction: column;
  background: #f7f7f7;
  overflow: hidden;
}

.edit-header {
  background: white;
  padding: 10px 24px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.edit-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.form-section {
  width: 50%;
  background: white;
  padding: 0px 20px;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
  position: relative;
  max-height: calc(100vh - 90px);
}

.form-content {
  flex: 1;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  min-height: 0;
  margin-top: 1rem;
}

/* 自定义滚动条样式 */
.form-content::-webkit-scrollbar {
  width: 8px;
}

.form-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.form-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
  border: 1px solid #f1f1f1;
}

.form-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.template-form {
  flex: 0 0 auto;
  padding: 0 4px;
}

.prompt-area {
  flex: 1 1 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  margin-bottom: 0;
  min-height: 0;
  overflow-y: auto;
  padding: 0 4px;
}

.system-prompt-textarea {
  flex: 1 1 0;
  min-height: 200px;
  max-height: none;
  resize: vertical;
  margin-bottom: 16px;
}

.prompt-label {
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #333;
}

.prompt-textarea {
  margin-bottom: 0;
}

.user-message-textarea {
  min-height: 60px;
  max-height: 120px;
  resize: vertical;
  margin-bottom: 0;
}

.form-actions-row {
  flex: 0 0 auto;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24px;
  padding: 8px 4px 16px;
  background-color: white;
  border-top: 1px solid #f0f0f0;
  position: sticky;
  bottom: 0;
  z-index: 10;
  height: 80px;
}

.model-switch-btn {
  flex-shrink: 0;
}

.form-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  align-items: center;
}

.preview-section {
  width: 50%;
  background: white;
  border-left: 1px solid #e0e0e0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  height: 100%;
}

.preview-header {
  padding: 0px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-shrink: 0;
  height: 48px;
  box-sizing: border-box;
}

.preview-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.preview-content {
  flex: 1;
  padding: 10px 24px 10px 10px;
  overflow-y: auto;
  overflow-x: hidden;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  justify-content: flex-start;
  min-height: 0;
  height: 100%;
  max-height: none;
}

.preview-content::-webkit-scrollbar {
  width: 6px;
}

.preview-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.preview-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.preview-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.empty-preview {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  text-align: center;
  width: 97%;
  height: 100%;
}

.preview-text {
  width: 100%;
  display: block;
  overflow: visible;
  height: auto;
}

.system-prompt {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  padding: 16px;
  margin-bottom: 24px;
  font-size: 14px;
  line-height: 1.6;
  color: #495057;
  white-space: pre-wrap;
  word-break: break-word;
}

.user-message {
  margin-bottom: 24px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .edit-content {
    flex-direction: column;
  }
  
  .form-section,
  .preview-section {
    width: 100%;
  }
  
  .preview-section {
    border-left: none;
    border-top: 1px solid #e0e0e0;
  }
}

.row-flex {
  display: flex;
  gap: 24px;
}
.flex-item {
  flex: 1;
}
</style>